﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace CNKI.TPI.Web.Base
{
    public class VideoStream
    {
        private readonly string _filename;
        private long startIndex = 0;
        private long endIndex = 0;
        public long FileLength { set; get; }
        public long ReadLength { set; get; }

        public VideoStream(string filename)
        {
            _filename = filename;
            //_filename = "D:\\Code\\TPI\\tpi6.5\\CNKI.TPI.Web\\CNKI.TPI.Web.UI\\Content\\mediaelementjs\\media\\000713_VTXHD.mov";
            FileLength = 0;
        }

        public VideoStream(string filename, long startIndex, long endIndex)
        {
            _filename = filename;
            //_filename = "D:\\Code\\TPI\\tpi6.5\\CNKI.TPI.Web\\CNKI.TPI.Web.UI\\Content\\mediaelementjs\\media\\000713_VTXHD.mov";
            this.startIndex = startIndex;
            this.endIndex = endIndex;
            try
            {
                FileLength = new FileInfo(_filename).Length;

                if (0 == endIndex)
                {
                    ReadLength = FileLength;
                }
                else
                {
                    ReadLength = endIndex - startIndex + 1;
                }
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }


        }

        public async void WriteToStream(Stream outputStream, HttpContent content, TransportContext context)
        {
            try
            {
                var buffer = new byte[524288];

                using (var video = File.Open(_filename, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    video.Seek(startIndex, SeekOrigin.Begin);

                    var bytesRead = 1;

                    long length = ReadLength;

                    while (length > 0 && bytesRead > 0)
                    {
                        bytesRead = video.Read(buffer, 0, (int)Math.Min(length, (long)buffer.Length));
                        await outputStream.WriteAsync(buffer, 0, bytesRead);
                        length -= bytesRead;
                    }
                }
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
                return;
            }
            finally
            {
                outputStream.Close();
            }
        }
    }
}
